<?php
namespace Protocols;
// 自动加载类
require_once __DIR__ . '/../../../vendor/autoload.php';
use Workerman\Connection\TcpConnection;
class App
{
    /**
     * Check the integrity of the package.
     *
     * @param string        $buffer
     * @param TcpConnection $connection
     * @return int
     */
    public static function input($buffer, TcpConnection $connection)
    {
        // Judge whether the package length exceeds the limit.
        if (strlen($buffer) >= TcpConnection::$maxPackageSize) {
            $connection->close();
            return 0;
        }
        //  Find the position of  "\n".
        $pos = strpos($buffer, "\n");
        // No "\n", packet length is unknown, continue to wait for the data so return 0.
        if ($pos === false) {
            return 0;
        }
        // Return the current package length.
        return $pos + 1;
    }

    /**
     * Encode.
     *
     * @param array $buffer
     * @return string
     */
    public static function encode($buffer)
    {
        if(is_array($buffer)){
            if($buffer['type'] == '57'){
                $data = json_encode([
                    'code'  => 'Succeed',
                    'type'  =>'transmit',
                    'msg'   => ' ',
                    'data'  =>[
                        'device_id' => $buffer['device_id'],
                        'group'     => $buffer['group'],
                        'content'   => $buffer['data']
                    ],
                ]);
//                var_dump("将硬件发来的数据打包成app格式");
//                var_dump($data);
//                var_dump("将硬件发来的数据打包成app格式");
                return $data . "\n";
            }
        }
        return $buffer . "\n";
    }

    /**
     * Decode.接收来的数据
     *
     * @param string $buffer
     * @return
     */
    public static function decode($buffer)
    {
        return trim($buffer);
    }
}
